const zoroDB = require('../util/zoroDB'),
  log = require('../util/log'),
  SQL_FIELDS = ['url', 'cache_date', 'html'];

exports.select = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  var sql = 'select * from cache where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  zoroDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      log(err)
      resolve([])
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = cache => {
  cache.url_id = cache.url
  delete cache.url
  cache.getUrl = function (resolve) {
    if (!!this.url) {
      resolve(this.url)
      return
    }
    require('./urlDao').select({
      id: this.url_id
    }, urls => {
      this.url = urls[0]
      resolve(this.url)
      if (urls.length > 1)
        log(this.url_id + '对应多个url')
    })
  }
}
